﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using Umbraco.Core.Persistence;
using Umbraco.Web.Mvc;
using Umbraco.Web.WebApi;
using UmbracoExtending.Order.Model;

namespace UmbracoExtending.Order.Controller
{
    /// <summary>
    /// 预约前端控制器
    /// </summary>
    [PluginController("UmbracoOrder")]
    public class FrontendDistrictController : UmbracoApiController
    {
        /// <summary>
        /// 返回全部省份信息
        /// </summary>
        /// <returns></returns>
        [AcceptVerbs("get")]
        public IEnumerable<DistrictItem> GetProvince()
        {
            var db = UmbracoContext.Application.DatabaseContext.Database;
            var query = new Sql().Select("[DistrictCode] as Code, [DistrictName] as Name")
                .From("[umbracoExtendingDistrict]")
                .Where("[ProvinceCode] = @0", "000000")
                .OrderBy("[DistrictCode]");

            return db.Fetch<DistrictItem>(query);
        }

        /// <summary>
        /// 返回城市信息
        /// </summary>
        /// <param name="province"></param>
        /// <returns></returns>
        public IEnumerable<DistrictItem> GetCity(string province)
        {
            var db = UmbracoContext.Application.DatabaseContext.Database;
            var query = new Sql().Select("[DistrictCode] as Code, [DistrictName] as Name")
                .From("[umbracoExtendingDistrict]")
                .Where("[ProvinceCode] = @0 AND [CityCode] = @1", province, "000000");

            //对于不显示三级的，同时城市仅有一个的，作为直辖市特殊处理
            int level = 2;
            if (level == 0)
            {
                var citys = db.Fetch<DistrictItem>(query);
                if (citys.Count == 1)
                {
                    query = new Sql().Select("[DistrictCode] as Code, [DistrictName] as Name")
                        .From("[umbracoExtendingDistrict]")
                        .Where("[ProvinceCode] = @0 AND [CityCode] = @1", province, citys.FirstOrDefault().Code)
                        .OrderBy("[DistrictCode]");
                    return db.Fetch<DistrictItem>(query);
                }
            }

            return db.Fetch<DistrictItem>(query.OrderBy("[DistrictCode]"));
        }

        /// <summary>
        /// 返回区级信息
        /// </summary>
        /// <param name="city"></param>
        /// <returns></returns>
        public IEnumerable<DistrictItem> GetDistrict(string city)
        {
            var db = UmbracoContext.Application.DatabaseContext.Database;
            var query = new Sql().Select("[DistrictCode] as Code, [DistrictName] as Name")
                .From("[umbracoExtendingDistrict]")
                .Where("[CityCode] = @0", city)
                .OrderBy("[DistrictCode]");

            return db.Fetch<DistrictItem>(query);
        }
    }
}
